import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:xws/helpers/my_selector.dart';
import 'package:xws/models/user/user_basic_info.dart';
import 'package:xws/res/icons.dart';
import 'package:xws/state/app_state.dart';
import 'package:xws/state/user_state.dart';
import 'package:xws/ui/notify/notify_page.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/app_img.dart';
import 'package:xws/widgets/refresh_widget/refresh_view.dart';

import 'account/account.dart';
import 'friends/friends.dart';
import 'goods/my_collect.dart';
import 'goods/my_get.dart';
import 'goods/my_pub.dart';
import 'settings/settings.dart';

enum _Funcs { notify, friends, account, settings }

extension _ExFuncs on _Funcs {
  String get str {
    switch (this) {
      case _Funcs.notify:
        return '通知';
      case _Funcs.friends:
        return '好友';
      case _Funcs.account:
        return '账户';
      case _Funcs.settings:
        return '设置';
      default:
        return '';
    }
  }

  IconData get icon {
    switch (this) {
      case _Funcs.notify:
        return IR.notify;
      case _Funcs.friends:
        return IR.friends;
      case _Funcs.account:
        return IR.me;
      case _Funcs.settings:
        return IR.settings;
      default:
        return IR.box;
    }
  }
}

/// 我的
class MinePage extends StatefulWidget {
  const MinePage({Key? key}) : super(key: key);

  @override
  _MinePageState createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  /// 点击功能项
  Future<void> _onFuncTap(_Funcs tag) async {
    switch (tag) {
      case _Funcs.notify:
        push(context, const NotifyPage());
        break;
      case _Funcs.friends:
        push(context, const FriendsPage());
        break;
      case _Funcs.account:
        push(context, const AccountPage());
        break;
      case _Funcs.settings:
        push(context, const Settings());
        break;
      default:
    }
  }

  @override
  Widget build(BuildContext context) {
    return RefreshView(
      onRefresh: (_) async {
        final UserBasicInfo? u = await us.updateBasicInfo();
        if (u != null) apps.setUnread(u.unreadMessageCount);
      },
      child: Column(
        children: <Widget>[_buildUser, _funcs],
      ),
    );
  }

  /// 用户块
  Widget get _buildUser {
    return ClipPath(
      clipper: const _HeaderClipper(),
      child: Container(
        width: sw,
        padding: const EdgeInsets.only(bottom: 26),
        color: white(context),
        child: Column(
          children: <Widget>[
            /// 通知图标
            Align(
              alignment: Alignment.topRight,
              child: Padding(
                padding: const EdgeInsets.all(6).copyWith(
                  top: statusBarHeight + 4,
                  bottom: 0,
                ),
                child: IconButton(
                  onPressed: () => push(context, const NotifyPage()),
                  padding: EdgeInsets.zero,
                  icon: Ms<AppState, int>.child(
                    selector: (AppState a) => a.unRead,
                    child: const Icon(IR.notify),
                    builder: (int c, Widget child) {
                      return Badge(
                        elevation: 0,
                        child: child,
                        showBadge: c > 0,
                        badgeContent: Container(
                          child: Text(
                            c > 99 ? '..' : c.toString(),
                            style: TextStyle(
                              color: white(context),
                              fontSize: 8,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          alignment: Alignment.center,
                          constraints: const BoxConstraints(
                            minWidth: 14,
                            minHeight: 14,
                          ),
                          decoration: BoxDecoration(
                            color: red(context),
                            shape: BoxShape.circle,
                          ),
                        ),
                        padding: const EdgeInsets.all(1),
                        position: const BadgePosition(top: -6, end: -4),
                        animationType: BadgeAnimationType.scale,
                        animationDuration: const Duration(milliseconds: 300),
                        badgeColor: white(context),
                      );
                    },
                  ),
                  color: black(context).withOpacity(0.5),
                ),
              ),
            ),

            /// 头像
            GestureDetector(
              onTap: () => _onFuncTap(_Funcs.account),
              child: Ms<UserState, UserBasicInfo>(
                selector: (UserState u) => u.info,
                shouldRebuild: (UserBasicInfo p, UserBasicInfo n) {
                  return p.avatarUrl != n.avatarUrl || p.gender != n.gender;
                },
                builder: (UserBasicInfo info) {
                  return Stack(
                    alignment: Alignment.bottomRight,
                    children: <Widget>[
                      AppImg.fitCover(
                        url: info.avatarUrl,
                        width: 90,
                        height: 90,
                        radius: 20,
                      ),
                      Container(
                        width: 20,
                        height: 20,
                        child: Icon(
                          info.gender == '男' ? IR.male : IR.fmale,
                          size: 12,
                          color: theme(context),
                        ),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          color: white(context),
                          borderRadius: const BorderRadius.only(topLeft: Radius.circular(10)),
                        ),
                      ),
                    ],
                  );
                },
              ),
            ),
            const SizedBox(height: 10),

            /// 昵称
            Ms<UserState, String>(
              selector: (UserState u) => u.info.nickName,
              builder: (String n) {
                return Text(
                  n,
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                );
              },
            ),
            const SizedBox(height: 8),

            /// 等级与积分
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                AppBtn(
                  onTap: () {},
                  child: Ms<UserState, int>(
                    selector: (UserState u) => u.info.level,
                    builder: (int l) {
                      return Text(
                        'Lv.$l',
                        style: TextStyle(
                          fontSize: 12,
                          color: white(context),
                        ),
                      );
                    },
                  ),
                  padding: const EdgeInsets.symmetric(horizontal: 8),
                  alignment: Alignment.center,
                  radius: 4,
                  height: 20,
                ),
                const SizedBox(width: 6),
                AppBtn(
                  onTap: () {},
                  child: Ms<UserState, int>(
                    selector: (UserState u) => u.info.integral,
                    builder: (int i) {
                      return Text(
                        '积分 : $i',
                        style: TextStyle(
                          fontSize: 12,
                          color: white(context),
                        ),
                      );
                    },
                  ),
                  padding: const EdgeInsets.symmetric(
                    horizontal: 8,
                  ),
                  alignment: Alignment.center,
                  radius: 4,
                  height: 20,
                  color: Colors.blueGrey,
                ),
              ],
            ),
            const SizedBox(height: 22),

            /// 物品数量
            Row(
              children: <Widget>[
                _buildGoodsInfoItem(
                  '已发布',
                  Ms<UserState, int>(
                    selector: (UserState u) => u.info.publishCount,
                    builder: (int c) => Text(
                      c.toString(),
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  onTap: () => push(context, const MyPub()),
                ),
                Container(
                  height: 20,
                  width: 0.5,
                  color: black(context).withOpacity(0.2),
                ),
                _buildGoodsInfoItem(
                  '已获得',
                  Ms<UserState, int>(
                    selector: (UserState u) => u.info.getCount,
                    builder: (int c) => Text(
                      c.toString(),
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  onTap: () => push(context, const MyGet()),
                ),
                Container(
                  height: 20,
                  width: 0.5,
                  color: black(context).withOpacity(0.2),
                ),
                _buildGoodsInfoItem(
                  '已收藏',
                  Ms<UserState, int>(
                    selector: (UserState u) => u.info.favoriteCount,
                    builder: (int c) => Text(
                      c.toString(),
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  onTap: () => push(context, const MyCollect()),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 用户物品功能块
  Widget _buildGoodsInfoItem(
    String text,
    Widget count, {
    Function()? onTap,
  }) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: ColoredBox(
          color: Colors.transparent,
          child: Column(
            children: <Widget>[
              count,
              Text(
                text,
                style: TextStyle(
                  fontSize: 12,
                  color: black(context).withOpacity(0.5),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 功能列表
  Widget get _funcs {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 14).copyWith(top: 6),
      child: Column(
        children: <Widget>[
          _buildFuncItem(bottomRadius: 0, tag: _Funcs.notify),
          _buildFuncItem(topRadius: 0, bottomRadius: 10),
          const SizedBox(height: 14),
          _buildFuncItem(bottomRadius: 0, tag: _Funcs.account),
          _buildFuncItem(topRadius: 0, bottomRadius: 10, tag: _Funcs.settings),
        ],
      ),
    );
  }

  /// 功能项
  Widget _buildFuncItem({
    double topRadius = 10,
    double bottomRadius = 0,
    _Funcs tag = _Funcs.friends,
  }) {
    Widget tail = Icon(
      Icons.arrow_forward_ios_rounded,
      size: 16,
      color: black(context).withOpacity(0.6),
    );

    if (tag == _Funcs.notify) {
      tail = Ms<AppState, int>.child(
        selector: (AppState a) => a.unRead,
        child: tail,
        builder: (int c, Widget child) {
          return Badge(
            elevation: 0,
            child: child,
            showBadge: c > 0,
            badgeContent: Container(
              child: Text(
                c > 99 ? '..' : c.toString(),
                style: TextStyle(
                  color: white(context),
                  fontSize: 8,
                  fontWeight: FontWeight.bold,
                ),
              ),
              alignment: Alignment.center,
              constraints: const BoxConstraints(
                minWidth: 16,
                minHeight: 16,
              ),
              decoration: BoxDecoration(
                color: red(context),
                shape: BoxShape.circle,
              ),
            ),
            padding: const EdgeInsets.all(1),
            position: const BadgePosition(top: 0, end: 0),
            animationType: BadgeAnimationType.scale,
            animationDuration: const Duration(milliseconds: 300),
            badgeColor: white(context),
          );
        },
      );
    }

    return AppBtn(
      onTap: () => _onFuncTap(tag),
      child: Row(
        children: <Widget>[
          Icon(
            tag.icon,
            size: 20,
            color: black(context).withOpacity(0.6),
          ),
          const SizedBox(width: 10),
          Text(
            tag.str,
            style: TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.bold,
              color: black(context).withOpacity(0.6),
            ),
          ),
          const Spacer(),
          tail,
        ],
      ),
      padding: const EdgeInsets.symmetric(horizontal: 20),
      alignment: Alignment.center,
      color: white(context),
      height: 56,
      borderRadius: BorderRadius.vertical(
        top: Radius.circular(topRadius),
        bottom: Radius.circular(bottomRadius),
      ),
    );
  }
}

/// 头部裁剪
class _HeaderClipper extends CustomClipper<Path> {
  const _HeaderClipper();

  @override
  Path getClip(Size size) {
    final double w = size.width;
    final double h = size.height;

    const double r = 10;

    return Path()
      ..moveTo(0, 0)
      ..lineTo(w, 0)
      ..lineTo(w, h)
      ..arcToPoint(
        Offset(w - r, h - r),
        radius: const Radius.circular(r),
        clockwise: false,
      )
      ..lineTo(r, h - r)
      ..arcToPoint(
        Offset(0, h),
        radius: const Radius.circular(r),
        clockwise: false,
      )
      ..close();
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}
